/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gui;

import carrental.Car;
import carrental.CarManagerImpl;
import carrental.Customer;
import carrental.CustomerManagerImpl;
import carrental.Lease;
import carrental.LeaseManagerImpl;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
import org.apache.commons.dbcp.BasicDataSource;

/**
 *
 * @author Johnny
 */
public class AddLeaseDialog extends javax.swing.JDialog {

    private final ResourceBundle labels;
    
    private class AddLeaseWorker extends SwingWorker<Void, Void> {
        private Lease c;

        public AddLeaseWorker(Lease c) {
            this.c = c;
        }
                
        @Override
        protected Void doInBackground() throws Exception {
            ((Index)getParent()).getLeasesManagerPanel().getTableModel().addLease(c);
            return null;
        }
        
        @Override
        protected void done(){
            dispose();
        }
    }
    
    /**
     * Creates new form AddLeaseDialog
     */
    public AddLeaseDialog(java.awt.Frame parent, boolean modal) {
        
        super(parent, modal);
        Locale locale = Locale.getDefault();
        labels = ResourceBundle.getBundle("labels",locale);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        carCombo = new javax.swing.JComboBox();
        customerCombo = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jDateSelector1 = new org.calendar.JDateSelector();
        jDateSelector2 = new org.calendar.JDateSelector();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(labels.getString("newLease"));
        setMinimumSize(new java.awt.Dimension(400, 200));
        setPreferredSize(new java.awt.Dimension(400, 200));

        jLabel1.setText(labels.getString("car")+":"
        );

        jLabel2.setText(labels.getString("customer")+":");

        jLabel3.setText(labels.getString("from")+":");

        jLabel4.setText(labels.getString("to")+":");

        CarManagerImpl manager = new CarManagerImpl();
        LeaseManagerImpl leaseManager = new LeaseManagerImpl();
        BasicDataSource ds = new BasicDataSource();
        Properties db = new Properties();
        try {
            db.load(Index.class.getResourceAsStream("/db.properties"));
        } catch (IOException ex) {
            Logger.getLogger(CarsTableModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        ds.setUrl(db.getProperty("jdbc.dbname"));
        manager.setDataSource(ds);
        leaseManager.setDataSource(ds);

        List<Car> list = leaseManager.unLeasedCars();
        ComboBoxObject[] cars;
        if(!list.isEmpty()){
            cars = new ComboBoxObject[list.size()];
            for(int i = 0; i < list.size(); i++){
                cars[i] = new ComboBoxObject(list.get(i).getNumberPlate(), list.get(i).getId());
            }
        } else {
            cars = new ComboBoxObject[1];
            cars[0] = new ComboBoxObject("No Cars!", -1);
        }
        carCombo.setModel(new javax.swing.DefaultComboBoxModel(cars));

        CustomerManagerImpl customerManager = new CustomerManagerImpl();
        customerManager.setDataSource(ds);

        List<Customer> customerList = customerManager.findAllCustomers();
        ComboBoxObject[] customers;
        if(!customerList.isEmpty()){
            customers = new ComboBoxObject[customerList.size()];
            for(int i = 0; i < customerList.size(); i++){
                customers[i] = new ComboBoxObject(customerList.get(i).getFirstName()+" " +customerList.get(i).getLastName(), customerList.get(i).getId());
            }
        } else {
            customers = new ComboBoxObject[1];
            customers[0] = new ComboBoxObject("No Customers!", -1);
        }
        customerCombo.setModel(new javax.swing.DefaultComboBoxModel(customers));

        jButton1.setText(labels.getString("ok"));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(labels.getString("cancel"));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(customerCombo, 0, 164, Short.MAX_VALUE)
                            .addComponent(carCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(27, 27, 27))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jDateSelector1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jDateSelector2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(51, 51, 51)
                .addComponent(jButton2)
                .addGap(89, 89, 89))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(carCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(customerCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jDateSelector1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jDateSelector2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(53, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        CarManagerImpl carManager = new CarManagerImpl();
        CustomerManagerImpl customerManager = new CustomerManagerImpl();
        
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl("jdbc:derby://localhost:1527/pv168");
        
        carManager.setDataSource(ds);
        customerManager.setDataSource(ds);
        
        Lease lease = new Lease();
        Car car = new Car();
        Customer customer = new Customer();
        
        car.setId(((ComboBoxObject)carCombo.getSelectedItem()).getId());
        customer.setId(((ComboBoxObject)customerCombo.getSelectedItem()).getId());
        
        lease.setCar(car);
        lease.setCustomer(customer);
        lease.setFromDate(jDateSelector1.getSelectedDate());
        lease.setToDate(jDateSelector2.getSelectedDate());
        
        new AddLeaseWorker(lease).execute();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddLeaseDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddLeaseDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddLeaseDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddLeaseDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AddLeaseDialog dialog = new AddLeaseDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox carCombo;
    private javax.swing.JComboBox customerCombo;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private org.calendar.JDateSelector jDateSelector1;
    private org.calendar.JDateSelector jDateSelector2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration//GEN-END:variables
}
